package com.zs.juc.thread;

import java.util.concurrent.*;

/**
 * @author madison
 * @description
 * @date 2021/6/1 17:27
 */
public class FutureTest1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<>(task) {
            // 异步任务执行完成，回调
            @Override
            protected void done() {
                try {
                    System.out.println("future.done():" + get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        };

        // 创建线程池（使用了预定义的配置）
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(futureTask);

        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }

        Thread.sleep(1000);
        // 可以取消异步任务
//        futureTask.cancel(true);

//        new Thread(futureTask).start();
        // 阻塞，等待异步任务执行完毕-获取异步任务的返回值
        System.out.println("future.get():" + futureTask.get());
        System.out.println(futureTask.get());
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.HOURS);
    }

    static class Task implements Callable<Integer> {
        // 返回异步任务的执行结果
        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "_" + i);
                Thread.sleep(500);
            }
            return i;
        }
    }
}
